package com.opdar.athena.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.ReferenceType;

import java.util.List;

/**
 * Created by shiju on 2017/7/1.
 */
public class JSONUtil {
    public static <T>T parseList(byte[] bytes, Class<?> clz){
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, clz);
            return objectMapper.readValue(bytes,javaType);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T>T parseObject(byte[] bytes,Class<T> clz){
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return objectMapper.readValue(bytes,clz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static byte[] toJSONAsBytes(Object o){
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsBytes(o);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
